using System;
using UnityEngine;

public class TurretProjectile : MonoBehaviour
{
    [SerializeField, Header("发射子弹的位置")]
    protected Transform projectileSpawnPosition;
    protected ObjectPooler pooler; // 对象池管理器
    protected Turret _turret;// 炮塔组件
    private Projectile _currentProjectileLoaded;// 当前装载的子弹

    [SerializeField, Header("攻击间隔")]
    protected float delayBtwAttacks = 2f;
    protected float _nextAttackTime;//下一次攻击时间

    [SerializeField, Header("子弹造成的伤害值")]
    protected float damage = 2f;
    public float Damge { get; set; }
    public float DelayPerShot { get; set; }

    private void Start()
    {
        pooler = GetComponent<ObjectPooler>(); // 获取对象池管理器组件
        _turret = GetComponent<Turret>();
        Damge = damage;
        DelayPerShot = delayBtwAttacks;
    }

    protected virtual void Update()
    {
        if (Time.time > _nextAttackTime)
        {
            // 如果有敌人目标且敌人目标的健康值大于0
            if (_turret.CurrentEnemyTarget != null && _turret.CurrentEnemyTarget._enemyHealth.CurrentHealth > 0f)
            {
                LoadProjectile();
                // 解除子弹的父节点关系
                _currentProjectileLoaded.transform.parent = null;
                // 设置子弹的目标敌人
                _currentProjectileLoaded.SetEnemy(_turret.CurrentEnemyTarget);
            }
            _nextAttackTime = Time.time + DelayPerShot;
        }
    }

    //加载子弹
    protected virtual void LoadProjectile()
    {
        GameObject newInstance = pooler.GetInstanceFromPool(); // 从对象池获取一个新的子弹实例
        newInstance.transform.localPosition = projectileSpawnPosition.position; // 设置子弹的位置为发射位置
        newInstance.transform.SetParent(projectileSpawnPosition); // 设置子弹的父节点为发射位置 
        _currentProjectileLoaded = newInstance.GetComponent<Projectile>();// 获取子弹组件
        _currentProjectileLoaded.Turretowner = this;
        _currentProjectileLoaded.ResetProjectile();//重置炮弹
        _currentProjectileLoaded.damage = Damge;

        newInstance.SetActive(true); // 激活子弹
    }

    //判断是否没有装载子弹
    // private bool IsTurretEmpty()
    // {
    //     return _currentProjectileLoaded == null;
    // }

    //重置装载的子弹
    public void ResetTurretProjectile()
    {
        _currentProjectileLoaded = null;
    }

}
